package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author 杨林
 * @create 2022-09-19 19:28 星期一
 * description:
 */
@Controller
@RequestMapping("/houseBroker")
public class HouseBrokerController extends BaseController {

    @Reference
    private HouseBrokerService houseBrokerService;

    @Reference
    private AdminService adminService;

    /**
     * 进入新增页面
     */

    @RequestMapping("/create")
    public String create(Model model,@RequestParam("houseId") Long hoseId){
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList", adminList);
        model.addAttribute("houseId",hoseId);
        return "houseBroker/create";
    }

    @RequestMapping("/save")
    public String save(HouseBroker houseBroker){
        //根据houseBroker查找Admin
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        //经纪人名称
        houseBroker.setBrokerName(admin.getName());
        //经纪人头像
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());

        houseBrokerService.insert(houseBroker);

        return "common/successPage";
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId,@PathVariable Long id){
        houseBrokerService.delete(id);
        return "redirect:/house/" + houseId;
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Long id,Model model){

        //根据id获取当前的houseBroker
        HouseBroker houseBroker = houseBrokerService.getById(id);

        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);

        model.addAttribute("houseBroker", houseBroker);

        return "houseBroker/edit";
    }


    @RequestMapping("/update")
    public String update(HouseBroker houseBroker){
        //根据houseBroker查找Admin
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        //经纪人名称
        houseBroker.setBrokerName(admin.getName());
        //经纪人头像
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());

        houseBrokerService.update(houseBroker);

        return "common/successPage";
    }

}
